package us.icitap.cm.business.ejb;

import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


import us.icitap.cm.business.AppUser;
import us.icitap.cm.business.entities.AppEntity;
import us.icitap.cm.business.entities.Case;
import us.icitap.cm.business.entities.EntityTypeEnum;
import us.icitap.cm.business.entities.Officer;
import us.icitap.cm.business.entities.OrgStructure;
import us.icitap.dao.IPersistenceFacade;
import us.icitap.timsportal.business.SimpleUser;
import us.icitap.utils.Result;

@Stateless
public class AppStatelessBean implements IAppStatelessBean {

	
	@EJB
	IAppPersistenceBean persistenceBean;
	
	
	@Override
	public IAppPersistenceBean getPersistenceBean(){
		return persistenceBean;
	}
	
	
	
	@Override
	public Result<AppUser> devLogin(){
		
		AppUser user = new AppUser();

		user.setUsername("APP_USER");
		user.setLoginDate(new Date());
	
		Officer officer = new Officer("9004482", "BLENDI JAHO");
		user.setOfficer(officer);
		
		Result<OrgStructure> result = this.getPersistenceBean().findEntityById(195, OrgStructure.class);
		if(result.isSucceeded()){
			user.setOrgStructure(result.getObject());
			officer.setOrgStructure(result.getObject());
		}
		
		
		return new Result<AppUser>(user, true, null);
		
	}
	
	@Override
	public Result<AppUser> login(SimpleUser u){
		
		AppUser user = new AppUser();

		user.setUsername(u.getUsername());
		user.setLoginDate(new Date());
		
		Result<OrgStructure> result = this.getPersistenceBean().findEntityById(u.getBaseStructure().getId(), OrgStructure.class);
		if(result.isSucceeded()){
			user.setOrgStructure(result.getObject());
			Result<Officer> res = this.getPersistenceBean().findEntityById(u.getOfficer().getOfficerId(), Officer.class);
			
			if(res.isSucceeded()){
				user.setOfficer(res.getObject());
				user.getOfficer().setOrgStructure(user.getOrgStructure());
				return new Result<AppUser>(user, true, null);
			}
			else{
				return new Result<AppUser>(null, false, res.getMessage());
			}	
		}
		else
			return new Result<AppUser>(null, false, result.getMessage());

	}
	
	
	
	@Override
	public Result<Case> saveCase(Case _case){
		try {
			
			
			Result<Case> result = this.getPersistenceBean().saveEntity(_case);
			if(result.isSucceeded()){
//				result.getObject().setAppEntitiesAsNotNewRecords();
			}
			return result;
		} catch (Exception e) {
			return new Result<Case>(null, false, e.getMessage());
		}
	}
	
	

	
	
}
